package com.mmm.station.security.method;

import com.mmm.station.security.entity.Manager;
import com.mmm.station.security.entity.Token;
import com.mmm.station.security.session.SessionUtils;
import com.mmm.station.security.utils.ContextHolderUtils;
import com.mmm.station.security.utils.SpringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by mmm on 2016/12/6.
 */
public class Subject {
    private Logger logger = LogManager.getLogger(this.getClass());

    private Manager manager;

    private static Subject instance;

    public Subject() {
    }

    public static Subject getInstance() {
        if (instance == null) {
            instance = new Subject();
            Manager manager = SpringUtil.getBean(Manager.class);
            Subject.getInstance().setManager(manager);

        }
        return instance;
    }

    public void setManager(Manager manager) {
        if (this.manager == null) {
            this.manager = manager;
        }
    }

    public Manager getManager() {
        return manager;
    }

    /**
     * 用户登录
     * 验证成功则为true
     *
     * @param username
     * @param password
     * @param conditions
     */
    public boolean login(Token token) {
        logger.info("进入login");
        Object user = manager.getRealm().getAnthInfo(token);
        if (user != null) {
            SessionUtils.getInstance().setAuthInfo(user);
            SessionUtils.getInstance().setPermission(manager.getRealm().getPermission(user));
            return true;
        }
        return false;
    }

    /**
     * 刷新用户权限
     */
    public void clearPermission() {
        SessionUtils.getInstance().clearPermission();

        SessionUtils.getInstance().setPermission(manager.getRealm().getPermission(SessionUtils.getInstance().getAuthInfo()));
    }

    /**
     * 注销
     */
    public void logout() {
        ContextHolderUtils.getSession().invalidate();
    }

}
